<template>
  <div class="vacation-box content-box">
    <nav-title v-if="edit" title="加班申请" :routerLink="routerLink" />
    <nav-title v-else title="加班审批" :routerLink="routerLink" />
    <div class="regulations-box" v-if="!edit">
      <div class="title">发起人信息</div>
      <simple-line title="员工ID" v-bind:value="allInfo.cWfEmplid" />
      <simple-line title="姓名" v-bind:value="allInfo.cWfName" />
      <simple-line title="部门" v-bind:value="allInfo.cWfDeptdescr" />
      <simple-line title="岗位" v-bind:value="allInfo.cWfJcDescr" />
      <simple-line title="职等" v-bind:value="allInfo.cWfJobLevel" />
    </div>
    <div class="regulations-box" v-if="!edit">
      <div class="title">申请人信息</div>
      <div class="applier-item" v-for="item in allInfo.appliers" v-bind:key="item">
        <simple-line title="姓名" v-bind:value="item.name" />
        <simple-line title="部门" v-bind:value="item.deptid" />
        <simple-line title="职等" v-bind:value="item.cJobLevel" />
      </div>
    </div>
    <div class="regulations-box vacation-content">
      <div class="title">流程信息</div>
      <div class="information">
        <edit-date-line :important="true" :boldtitle="true" label="加班开始时间" :readonly="!edit" v-model="allInfo.date1"
          @on-change="startDateChange()" />

        <div class="info-cell clearfix time-picker">
          <div class="half_option" :class="edit ? 'value date' : 'value'">
            <group label-width="5em">
              <popup-radio placeholder="请选择小时" :options="cHours" :readonly="!edit" v-model="allInfo.cHour"></popup-radio>
            </group>
          </div>
          <div class="half_option" :class="edit ? 'value date' : 'value'">
            <group label-width="5em">
              <popup-radio placeholder="请选择分" :options="cMinute2s" :readonly="!edit" v-model="allInfo.cMinute2"></popup-radio>
            </group>
          </div>
        </div>
        <edit-date-line :important="true" :boldtitle="true" label="加班结束时间" :readonly="!edit" v-model="allInfo.date2"
          @on-change="endDataChange()" />

        <div class="info-cell clearfix time-picker">
          <div class="half_option" :class="edit ? 'value date' : 'value'">
            <group label-width="5em">
              <popup-radio placeholder="请选择" :options="cHour1s" :readonly="!edit" v-model="allInfo.cHour1"></popup-radio>
            </group>
          </div>
          <div class="half_option" :class="edit ? 'value date' : 'value'">
            <group label-width="5em">
              <popup-radio placeholder="请选择" :options="cMinute3s" :readonly="!edit" v-model="allInfo.cMinute3"></popup-radio>
            </group>
          </div>
        </div>
        <edit-option-line :important="true" :boldtitle="true" label="刷卡类型" :readonly="!edit" :vals="cCardTypes" v-model="allInfo.cCardType" />

        <file-line v-if="!edit" label="附件" :fileitems="allInfo.wfFiles" :boldtitle="true" />
      </div>
    </div>
    <div class="regulations-box">
      <div class="regulations-box">
        <div class="info-label">加班事由</div>
        <div class="info-label-text">
          <textarea v-if="edit" placeholder="请在这里输入..." rows="5" v-model="allInfo.cApplInfo"></textarea>
          <textarea v-else="" readonly rows="5" v-model="allInfo.cApplInfo"></textarea>
        </div>
      </div>
    </div>
    <div v-if="edit" class="regulations-box">
      <div class="regulations-box">
        <div class="info-label">附件</div>
        <div class="file-list" v-for="item in fileList">
          <div class="filname">
            <span class="iplodimg">
              <a v-if="(allInfo.fileType == 'jpg') || (item.fileType == 'png') || (item.fileType == 'pdf') || (item.fileType=='txt') || (item.fileType=='jpeg') "
                href="javascript:;" @click="showItemClick(item)">{{item.originalName}}</a>
              <!-- <a v-else="" href="javascript:;" @click="downloadFile(item.fileUrl)">{{item.originalName}}</a> -->
              <a v-else="" href="javascript:;" @click="openApp(item.fileUrl, item.androidUrl)">{{item.originalName}}</a>
              <img class="delicon" v-if="edit" @click="delImg(item.seqnbr)" src="../vacation/images/delfil.png">
            </span>
          </div>
        </div>
        <div class="wrap-load" v-if="edit">
          <div class="upload-part">
            <img src="../vacation/images/addfils.png">
            <input @change="uploadFile" type="file" name="file" id="file" accept="image/*">
          </div>
        </div>
      </div>
    </div>

    <div class="regulations-box">
      <div class="title">分权引用</div>
      <fqyy-line :editting="edit" :fqyyFlag="fqyyInfo.cFqyyFlag" :noFqyySum="fqyyInfo.noFqyySum" :noFqyyRatio="fqyyInfo.noFqyyRatio"
        :fqyyMsg="fqyyInfo.cFqyyDetail" ref="fqyy"></fqyy-line>
    </div>

    <show-annex :option="showItem" v-if="showDetail" :hiddenImg="hiddenImg"></show-annex>

    <button v-if="resubmit" @click="submit">重新提交</button>
    <button v-else-if="edit" @click="submit">提交</button>

    <!-- 流程图 -->
    <div class="regulations-box" v-if="!edit">
      <div class="title">流程图</div>
      <v-flow-charts :transNum="cTransactionNbr" :loginOprid="loginOprid"></v-flow-charts>
    </div>
    <!-- 审批意见 -->
    <div class="regulations-box" v-if="approved == '0'&&allInfo.cStepType!='C' && allInfo.cIsChuanyue != 'Y'">
      <div class="info-label">审批意见</div>
      <div class="info-label-text">
        <textarea v-if="approved == '0'" placeholder="请在这里输入..." rows="5" v-model="cComments"></textarea>
        <textarea v-else="" readonly rows="5" v-model="cComments"></textarea>
      </div>
    </div>

    <div style="height: 50px" v-if="!edit"></div>
    <!-- 底部按钮 -->
    <div v-if="approved == '0'">
      <operation-btn :cApprovalSw="allInfo.cApprovalSw" :cDenySw="allInfo.cDenySw" :cPushbackAllSw="allInfo.cPushbackAllSw"
        :cAddSw="allInfo.cAddSw" :cTransactionNbr="allInfo.cTransactionNbr" :cWfType="allInfo.cWfType" :cReadSw="allInfo.cIsChuanyue"
        :cStepType="allInfo.cStepType" :cComments="cComments"></operation-btn>
    </div>
  </div>
</template>

<script>
  import { Datetime, Group, PopupRadio, dateFormat } from "vux";
import {
  getDicItem,
  getCompensateApprove,
  saveOvrt,
  getWfOvrtHdr,
  delWfFile,
  getFqyyInfo,
  saveFqyyInfo
} from "../../api/api";
import fqyyLine from "../../components/basic/FqyyLine"
import CommonUtil from '../../components/basic/util'
import FileLine from '../../components/basic/FileLine'
import EditOptionLine from '../../components/basic/EditOptionLine'
import EditDateLine from '../../components/basic/EditDateLine'
import SimpleLine from '../../components/basic/SimpleLine'
import { imgPreview, postImg } from "../../util/uploadImg";
import operationBtn from "../formalStaff/common/operationBtn";
import qs from "qs";
import moment from "moment";
import cloneDeep from "lodash/clonedeep";
import vFlowCharts from "../formalStaff/common/flowChart";
import { publicUrl } from "../../util/http";
export default {
  name: "OverTime",
  components: {
    operationBtn,
    Datetime,
    Group,
    PopupRadio,
    vFlowCharts,
    EditOptionLine,
    EditDateLine,
    SimpleLine,
    FileLine,
    fqyyLine
  },
  created() {

  },
  mounted() {
    CommonUtil.tryLogin(this).then(()=>{
      this.cTransactionNbr = this.$route.query.cTransactionNbr;
      this.approved = this.$route.query.approved;
      this.loginOprid = this.$route.query.token;
      if (this.$route.query.approved || this.$route.query.approved == 0) {
        this.getData();
        this.edit = false;
      } else {
        if (this.$route.query.cTransactionNbr) {
          this.getData();
          this.resubmit = true;
        }
      }
      this.cWfType = "OVRT";
      getFqyyInfo({'cTransactionNbr':this.cTransactionNbr,'processType':'overTime'}).then(res => {
          this.fqyyInfo = res.retData;

      })

      CommonUtil.loadDic(this.cCardTypes, 'C_CARD_TYPE', "xlatshortname","fieldvalue")
      CommonUtil.loadDic(this.cHours, 'C_HOUR', "xlatshortname","fieldvalue")
      CommonUtil.loadDic(this.cMinute2s, 'C_MINUTE2', "xlatshortname","fieldvalue")
      CommonUtil.loadDic(this.cHour1s, 'C_HOUR1', "xlatshortname","fieldvalue")
      CommonUtil.loadDic(this.cMinute3s, 'C_MINUTE3', "xlatshortname","fieldvalue")
    })
  },
  data() {
    return {
      fqyyInfo:{
        fqyyFlag:'',
        fqyyDetail:''
      },
      cCardTypes:[],
      cHours:[],
      cMinute2s:[],
      cHour1s:[],
      cMinute3s:[],

      allInfo: {
        cCardType:'',
        date1:'',
        cHour:'',
        cMinute2:'',
        date2:'',
        cHour1:'',
        cMinute3:'',
        cYesNo:'',
        cApplInfo:''
      },

      publicUrl: publicUrl,
      resubmit: false,
      routerLink: "",
      approved: "",
      edit: true,
      leaveInfo: "",
      cComments: "",

      cWfType: "",
      fileList: [],
      cTransactionNbr: "",
      showItem: {},
      showDetail: false,
      showGroup: false,
    };
  },
  methods: {
    getData() {
      this.$vux.loading.show();
      getWfOvrtHdr({
        cTransactionNbr: this.cTransactionNbr,
        loginOprid: this.loginOprid
      })
        .then(res => {
           console.log(res);
          this.$vux.loading.hide();
          if (res && res.retCode === "000000") {
            CommonUtil.updateFileUrl(res.retData.wfFiles);
            this.allInfo = res.retData;
            const newRes = Object.assign({}, res.retData);
            newRes.leaves &&
              newRes.leaves.map(item => {
                item.ovrtTypeList = this.defaultObj.ovrtTypeList;
                item.endModeList = this.defaultObj.endModeList;
              });
            this.list = newRes.leaves;
            document.documentElement.scrollTop = 0;
            this.leaveInfo = newRes.leaveInfo;
            this.cWfType = newRes.cWfType;
            this.fileList = res.retData.wfFiles;
          } else {
            this.$vux.alert.show({
              title: "提示",
              content: res.retMsg
            });
          }
        })
        .catch(res => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "警告",
            content: "网络异常，请稍后重试"
          });
        });
    },
    startDateChange() {
		if(this.edit) {
		  if ( moment(this.allInfo.date1).unix() > moment(this.allInfo.date2).unix()) {
			return this.$vux.alert.show({
			  title: "提示",
			  content: "开始日期必须小于或等于结束日期！",
			  onHide: () => {
				this.allInfo.date1 = this.allInfo.date2;
			  }
			});
		  }
		}
    },
    endDataChange() {
      if(this.edit) {
        if ( moment(this.allInfo.date1).unix() > moment(this.allInfo.date2).unix()) {
        return this.$vux.alert.show({
          title: "提示",
          content: "结束日期必须大于或等于开始日期！",
          onHide: () => {
          this.allInfo.date2 = this.allInfo.date1;
          }
        });
        }
      }
    },
    submit() {
      if(!CommonUtil.valid(this, this.allInfo, "cCardType", "请选择刷卡类型")
      ||!CommonUtil.valid(this, this.allInfo, "date1", "请选择开始日期")
      ||!CommonUtil.valid(this, this.allInfo, "cHour", "请完善开始时间")
      ||!CommonUtil.valid(this, this.allInfo, "cMinute2", "请完善开始时间")
      ||!CommonUtil.valid(this, this.allInfo, "date2", "请选择结束日期")
      ||!CommonUtil.valid(this, this.allInfo, "cHour1", "请完善开始时间")
      ||!CommonUtil.valid(this, this.allInfo, "cMinute3", "请完善开始时间")
      ||!CommonUtil.valid(this, this.allInfo, "cApplInfo", "请填写加班事由！")
      ) {
        return;
      }

      if(!this.$refs.fqyy.fqyyFlag1 || (this.$refs.fqyy.fqyyFlag1[0] == '有' && !this.$refs.fqyy.fqyyMsg1)){
        this.$vux.alert.show({
          title: "提示",
          content: "分权信息不能为空"
        });
        return;
      }

      this.$vux.loading.show();
      if(!this.allInfo.cTransactionNbr) {
        this.allInfo.cTransactionNbr = this.cTransactionNbr;
      }
      saveOvrt(this.allInfo)
        .then(res => {
          //保存分权信息
          saveFqyyInfo({
            cTransactionNbr:res.retData,
            cFqyyFlag:this.$refs.fqyy.fqyyFlag1[0],
            cFqyyDetail:this.$refs.fqyy.fqyyMsg1
          }).then(res => {
              console.log('分权',res);
          });
          this.$vux.loading.hide();
          if (res && res.retCode === "000000") {
            this.$vux.alert.show({
              title: "成功",
              content: "申请成功",
              onHide: () => {
                // this.fileList = [];
                // this.approved = 2;
                // this.routerLink = "MyApplication";
                // this.cTransactionNbr = res.retData;
                // this.edit = false;
                // this.resubmit = false;
                // this.getData();
                this.$router.push({ name:'MyApplication'});
              }
            });
          } else {
            this.$vux.alert.show({
              title: "提示",
              content: res.retMsg
            });
          }
        })
        .catch(res => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "警告",
            content: "网络异常，请稍后重试"
          });
        });
    },
    startTimeChange(index) {
      if (!this.list[index].endDttm || !this.list[index].enddttmMode) return;
      if (this.list[index].enddttmMode == "B") {
        return (this.list[index].durationDays =
          parseInt(
            (moment(`2008-08-09 ${this.list[index].endDttm}`).unix() -
              moment(`2008-08-08 ${this.list[index].startDttm}`).unix()) /
              36
          ) / 100);
      } else if (
        moment(`2008-08-08 ${this.list[index].startDttm}`).unix() >
        moment(`2008-08-08 ${this.list[index].endDttm}`).unix()
      ) {
        return this.$vux.alert.show({
          title: "提示",
          content: "开始时间必须小于或等于结束时间！",
          onHide: () => {
            this.list[index].startDttm = this.list[index].endDttm;
            this.list[index].durationDays = 0;
          }
        });
      } else {
        this.list[index].durationDays =
          parseInt(
            (moment(`2008-08-08 ${this.list[index].endDttm}`).unix() -
              moment(`2008-08-08 ${this.list[index].startDttm}`).unix()) /
              36
          ) / 100;
      }
    },
    endTimeChange(index) {
      if (!this.list[index].startDttm || !this.list[index].enddttmMode) return;
      if (this.list[index].enddttmMode == "B") {
        return (this.list[index].durationDays =
          parseInt(
            (moment(`2008-08-09 ${this.list[index].endDttm}`).unix() -
              moment(`2008-08-08 ${this.list[index].startDttm}`).unix()) /
              36
          ) / 100);
      } else if (
        moment(`2008-08-08 ${this.list[index].startDttm}`).unix() >
        moment(`2008-08-08 ${this.list[index].endDttm}`).unix()
      ) {
        return this.$vux.alert.show({
          title: "提示",
          content: "结束时间必须大于或等于开始时间！",
          onHide: () => {
            this.list[index].endDttm = this.list[index].startDttm;
            this.list[index].durationDays = 0;
          }
        });
      } else {
        this.list[index].durationDays =
          parseInt(
            (moment(`2008-08-08 ${this.list[index].endDttm}`).unix() -
              moment(`2008-08-08 ${this.list[index].startDttm}`).unix()) /
              36
          ) / 100;
      }
    },
    dayChange(index) {
      if (!this.list[index].startDttm || !this.list[index].endDttm) return;
      if (this.list[index].enddttmMode == "B") {
        return (this.list[index].durationDays =
          parseInt(
            (moment(`2008-08-09 ${this.list[index].endDttm}`).unix() -
              moment(`2008-08-08 ${this.list[index].startDttm}`).unix()) /
              36
          ) / 100);
      } else if (
        moment(`2008-08-08 ${this.list[index].startDttm}`).unix() >
        moment(`2008-08-08 ${this.list[index].endDttm}`).unix()
      ) {
        return this.$vux.alert.show({
          title: "提示",
          content: "结束时间必须大于或等于开始时间！",
          onHide: () => {
            this.list[index].endDttm = this.list[index].startDttm;
            this.list[index].durationDays = 0;
          }
        });
      } else {
        this.list[index].durationDays =
          parseInt(
            (moment(`2008-08-08 ${this.list[index].endDttm}`).unix() -
              moment(`2008-08-08 ${this.list[index].startDttm}`).unix()) /
              36
          ) / 100;
      }
    },

    delImg(index) {
      delWfFile(
        qs.stringify({ cTransactionNbr: this.cTransactionNbr, seqnbr: index })
      )
        .then(res => {
          if (res.retCode === "000000") {
            const newList = [];
            this.fileList.map(item => {
              if (item.seqnbr != index) newList.push(item);
            });
            this.fileList = newList;
            this.$vux.alert.show({
              title: "提示",
              content: "删除成功"
            });
          } else {
            this.$vux.alert.show({
              title: "提示",
              content: res.retMsg
            });
          }
        })
        .catch(e => {
          this.$vux.loading.hide();
          this.$vux.alert.show({
            title: "提示",
            content: "上传失败"
          });
        });
    },
    showItemClick(item) {
      this.showItem = item;
      this.showDetail = true;
    },
    hiddenImg() {
      this.showDetail = false;
    },
    // downloadFile(url) {
    //   let form = document.createElement('form');
    //   form.action = url;
    //   form.method = 'get';
    //   document.body.appendChild(form);
    //   form.submit();
    //   form.remove();
    //   this.$vux.alert.show({
    //     title: "提示",
    //     content: "文件下载成功！"
    //   });
    // },
    uploadFile(e) {
      let files = e.target.files || e.dataTransfer.files;
      if (!files.length) return;
      this.picValue = files[0];
      // let haveImg = false;
      // this.fileList.map((item)=>{
      //   if (item.originalName == this.picValue.name) return haveImg = true;
      // });
      // if (haveImg) {
      //   return this.$vux.alert.show({
      //           title: "提示",
      //           content: "请不要重复上传！"
      //         });
      // }
      this.$vux.loading.show({
        text: "上传中"
      });
      imgPreview(this.picValue).then(imgRes => {
        postImg(imgRes, this.cTransactionNbr, this.cWfType, this.picValue.name)
          .then(res => {
            this.$vux.loading.hide();
            if (res.retCode === "000000") {
              this.cTransactionNbr = res.retData.cTransactionNbr;
              const file = document.getElementById("file");
              file.value = "";
              const obj = {
                originalName: this.picValue.name,
                fileUrl: imgRes,
                seqnbr: res.retData.seqnbr,
                fileType: this.picValue.name.split(".")[1]
              };
              this.fileList.push(obj);
              this.$vux.alert.show({
                title: "提示",
                content: "上传成功"
              });
            } else {
              this.$vux.alert.show({
                title: "提示",
                content: res.retMsg
              });
            }
          })
          .catch(e => {
            this.$vux.loading.hide();
            this.$vux.alert.show({
              title: "提示",
              content: "上传失败"
            });
          });
      });
    },
    openApp(url, androidUrl) {
      const u = navigator.userAgent;
      const isAndroid = u.indexOf("Android") > -1 || u.indexOf("Adr") > -1; //android终端
      const isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
      if (isAndroid) {
        webview.openAttachmentWebView(
          `${this.publicUrl}${androidUrl}`,
          this.$store.state.oprId,
          ""
        ); // eslint-disable-line
      } else {
        window.location.href = `myapp:${this.publicUrl}${url}`;
      }
    }
  }
};
</script>

<style type="text/scss" lang="scss">
  @import "../vacation/vacation.scss";
@import "../../styles/rejectmain.scss";
.time-picker{
  padding:0 30px;
  border-bottom: 1px solid #e5e5e5;
  .half_option{
    box-sizing: border-box;
    width: 35%;
    margin: 10px 5%;
    float: left;
    border: 1px solid #eee;
  }
}
.content-box .regulations-box .value .weui-cell {
  padding: 3px 10px !important;
}
</style>
